import 'dart:convert';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_wanandroid/httpUtils/http_util.dart';
import 'package:flutter_wanandroid/pages/flutter_webview.dart';
import 'package:flutter_wanandroid/pages/tree_detail_page.dart';
import 'package:flutter_wanandroid/res/colors.dart';
import 'package:fluttertoast/fluttertoast.dart';

import '../common/api.dart';
import '../http/tree_entity.dart';

class TreePage extends StatefulWidget {
  const TreePage({Key? key}) : super(key: key);

  @override
  State<TreePage> createState() => _TreePageState();
}

class _TreePageState extends State<TreePage> {
  List<IconData> _icons = [
    Icons.star_border,
    Icons.child_care,
    Icons.cloud_queue,
    Icons.ac_unit,
    Icons.lightbulb_outline,
  ];
  List<DataBean>? _data = [];

  ScrollController _controller = ScrollController();
  int _panelIndex = 0; //展开下标

  @override
  void initState() {
    super.initState();
    _controller.addListener(() {
      if (_controller.position.pixels == _controller.position.maxScrollExtent) {
        Fluttertoast.showToast(msg: "已经滑动到最后一页");
      }
    });
    getHttp();
  }

  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
        color: Theme.of(context).primaryColor,
        displacement: 40,
        child: SingleChildScrollView(
          controller: _controller,
          child: ExpansionPanelList(
            //开关动画时长
            animationDuration: Duration(milliseconds: 500),
            //开关回调
            expansionCallback: (panelIndex, isExpanded) {
              if (mounted) {
                setState(
                  () {
                    _panelIndex = panelIndex;
                    _data?[panelIndex].isExpanded = !isExpanded;
                  },
                );
              }
            },
            //内容区
            children: _data!.map<ExpansionPanel>((e) {
              return ExpansionPanel(
                  ////标题
                  headerBuilder: (context, isExpanded) {
                    return ListTile(
                      contentPadding: EdgeInsets.all(10),
                      title: Text(
                        e.name ?? "",
                        style: TextStyle(color: Theme.of(context).primaryColor),
                      ),
                      //取随机icon
                      leading: Icon(_icons[Random().nextInt(_icons.length)]),
                    );
                  },
                  //展开内容
                  body: Container(
                    height: 200,
                    child: ListView.builder(
                      itemCount: e.children?.length,
                      itemBuilder: (context, index) {
                        return GestureDetector(
                          child: ListTile(
                            title: Text(
                              e.children?[index].name ?? "",
                              style: const TextStyle(color: YColors.color_999),
                            ),
                            trailing: const Icon(Icons.chevron_right),
                            // onTap: () {
                            //   Fluttertoast.showToast(msg: "跳转到下一页");
                            // },
                          ),
                          onTap: () {
                            Fluttertoast.showToast(msg: "跳转到下一页");
                            Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                              return TreeDetailPage(title: e.name ?? "", currentIndex: index);
                            }));
                          },
                        );
                      },
                    ),
                  ),
                  isExpanded: e.isExpanded ?? false);
            }).toList(),
          ),
        ),
        onRefresh: () async {
          Future.delayed(const Duration(seconds: 1), () {
            Fluttertoast.showToast(msg: "下拉刷新");
          });
        });
  }

  // @override
  // Widget build(BuildContext context) {
  //   return Scaffold(
  //       body: RefreshIndicator(
  //     color: Theme.of(context).primaryColor,
  //     onRefresh: () async {
  //       Future.delayed(Duration(seconds: 1), () {
  //         Fluttertoast.showToast(msg: "下拉刷新");
  //       });
  //     },
  //     child: ListView.builder(
  //         controller: _controller,
  //         itemCount: _data?.length,
  //         itemBuilder: (context, i) {
  //           List<ChildrenBean>? _children = _data?[i].children;
  //           return Column(
  //             children: [
  //               ListTile(
  //                 leading: Icon(_icons[Random().nextInt(_icons.length)]),
  //                 title: Text(
  //                   _data?[i].name ?? "",
  //                   style: TextStyle(color: Theme.of(context).primaryColor),
  //                 ),
  //                 trailing: _data?[i].isExpanded == true
  //                     ? Icon(Icons.keyboard_arrow_down)
  //                     : Icon(Icons.keyboard_arrow_up),
  //                 onTap: () {
  //                   if (mounted) {
  //                     setState(() {
  //                       if (_data != null &&
  //                           _data?[i] != null &&
  //                           _data?[i].isExpanded != null) {
  //                         _data?[i].isExpanded = !_data![i].isExpanded!;
  //                       }
  //                     });
  //                   }
  //                 },
  //               ),
  //               _data?[i].isExpanded == true
  //                   ? (Container(
  //                       height: 200,
  //                       child: ListView.builder(
  //                         itemCount: _children?.length,
  //                         itemBuilder: (context, index) {
  //                           return ListTile(
  //                             title: Text(
  //                               _children?[index].name ?? "",
  //                               style:
  //                                   const TextStyle(color: YColors.color_999),
  //                             ),
  //                             trailing: const Icon(Icons.chevron_right),
  //                             onTap: () {
  //                               Fluttertoast.showToast(msg: "跳转到下一页");
  //                             },
  //                           );
  //                         },
  //                       ),
  //                     ))
  //                   : Container(),
  //             ],
  //           );
  //         }),
  //   ));
  // }

  void getHttp() async {
    var name = await HttpUtil().get(Api.TREE);
    Map<String, dynamic> map = json.decode(name.toString());
    TreeEntity? fromMap = TreeEntity.fromMap(map);
    if (mounted) {
      setState(() {
        if (fromMap != null) {
          var data = fromMap.data;
          data?.forEach((element) {
            element.isExpanded = false;
          });
          _data = data;
        }
      });
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
}
